package com.echat.messagesender.sender.sms.bean.smsway;

import com.echat.messagesender.sender.util.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
 *author:a276202460
 *create date:Aug 27, 2011
 *创建一个简单的xml-bean解析映射工具类，如果需要复杂bean的解析请使用dom包做详细的解析
 */
public class SimpleXmlParserForWeiXin {
    private static SAXParserFactory factory;

    private static final Object mutex = new Object();

    private static SAXParserFactory getFactory() {
        if (factory == null) {
            synchronized (mutex) {
                if (factory == null)
                    factory = SAXParserFactory.newInstance();
            }
        }
        return factory;
    }

    private static SAXParser getParser() throws ParserConfigurationException,
            SAXException {
        return getFactory().newSAXParser();
    }

    private static XMLReader getXMLReader() throws SAXException,
            ParserConfigurationException {
        return getParser().getXMLReader();
    }

    public static Object parseXmlToBean(String filepath, Class beanclass,
                                        String nodename) throws Exception {
        return parseXmlToBean(new File(filepath), beanclass, nodename);
    }

    public static Object parseXmlToBean(File file, Class beanclass,
                                        String nodename) throws Exception {
        if (file == null || !file.exists()) {
            throw new Exception("file not found exception");
        }
        return parseXmlToBean(new FileInputStream(file), beanclass, nodename);
    }

    public static Object parseXmlToBean(InputStream input, Class beanclass,
                                        String nodename) throws Exception {
        try {
            Document xmldoc = getXMLDocument(input);
            Element root = xmldoc.getRootElement();
            Element beanelement = root.element(nodename);
            return getElementBean(beanelement, beanclass);
        } finally {
            input.close();
        }
    }

    public static Object parseXmlContentToBean(String xmlContent, Class beanclass,
                                               String nodename) throws Exception {

        Document xmldoc = getXMLDocument(xmlContent);
        Element root = xmldoc.getRootElement();
        Element beanelement = null;
        if (StringUtils.isNotEmpty(nodename)) {
            beanelement = root.element(nodename);
        } else {
            beanelement = root;
        }
        return getElementBean(beanelement, beanclass);

    }

    public static Map<String, String> parseXmlContentToMap(String xmlContent) throws Exception {

        Document xmldoc = getXMLDocument(xmlContent);
        Element root = xmldoc.getRootElement();
        List<Element> elementList = root.elements();
        if (elementList == null) {
            return null;
        }
        Map<String, String> map = new HashMap();
        for (Element e : elementList) {
            map.put(e.getName(), e.getText().trim());
        }
        return map;

    }

    public static List parseXmlToBeanlist(File file,
                                          Class beanclass, String nodename) throws Exception {
        if (file == null || !file.exists()) {
            throw new Exception("file not found exception");
        }
        return parseXmlToBeanlist(new FileInputStream(file), beanclass, nodename);
    }

    public static List parseXmlToBeanlist(String filepath,
                                          Class beanclass, String nodename) throws Exception {
        return parseXmlToBeanlist(new File(filepath), beanclass, nodename);
    }

    public static List parseXmlToBeanlist(InputStream input,
                                          Class beanclass, String nodename) throws Exception {
        try {
            Document xmldoc = getXMLDocument(input);
            Element root = xmldoc.getRootElement();
            return parseToBeanList(beanclass, root, nodename);
        } finally {
            input.close();
        }

    }

    private static List<Object> parseToBeanList(Class beanclass, Element root, String nodeName) throws Exception {
        if (root == null) {
            return null;
        }
        List<Element> beannodelist = root.elements(nodeName);
        List<Object> rs = new ArrayList<Object>();
        for (Element beanelement : beannodelist) {
            rs.add(getElementBean(beanelement, beanclass));
        }

        return rs;
    }

    private static Object getElementBean(Element beanelement, Class beanclass)
            throws Exception {

        Field[] beanfields = beanclass.getDeclaredFields();

        Object bean = beanclass.newInstance();
        while (beanclass != null) {
            beanfields = beanclass.getDeclaredFields();
            for (Field f : beanfields) {
                setPeroperty(f, bean, beanclass, beanelement);
            }
            beanclass = beanclass.getSuperclass();
        }


        return bean;
    }

    private static void setPeroperty(Field f, Object bean, Class beanClass, Element beanelement)
            throws Exception {
        Class type = f.getType();
        String fieldname = f.getName();
        fieldname = fieldname.substring(0, 1).toUpperCase()
                + (fieldname.length() > 1 ? fieldname.substring(1) : "");
        String setmethodname = getSetterMethodname(fieldname);
        Method method = null;
        try {
            method = beanClass.getMethod(setmethodname, type);
        } catch (NoSuchMethodException e) {
            return;
        }
        boolean stringList = false;
        if (type == List.class) {
            Field field = Field.class.getDeclaredField("signature");
            field.setAccessible(true);
            String listSignature = field.get(f).toString();
            String listBeanClass = listSignature.replace("Ljava/util/List<L", "").replace(";>;", "").replaceAll("/", ".");

            if (listBeanClass.equals("java.lang.Object") || listBeanClass.equals("java.lang.String")) {
                stringList = true;
            } else {
                Class beanclass = Class.forName(listBeanClass);
                //System.out.println(beanclass.getSimpleName().toLowerCase());
                List<Object> beanList = parseToBeanList(beanclass, beanelement.element(fieldname), beanclass.getSimpleName().toLowerCase());
                method.invoke(bean, new Object[]{beanList});
                return;
            }
//			System.out.println(listBeanClass);
//			System.out.println(Class.forName(listBeanClass));
        }
        if (stringList || type.getSimpleName().equals("String[]")) {
            Element listnode = beanelement.element(fieldname);
            if (listnode != null) {
                List<Element> listemelents = listnode.elements();
                ArrayList paramlist = new ArrayList();
                for (Element el : listemelents) {
                    paramlist.add(el.getText().trim().replaceAll("\\n", ""));
                }
                if (type == List.class)
                    method.invoke(bean, new Object[]{paramlist});
                else
                    method.invoke(bean, new Object[]{(String[]) paramlist.toArray(new String[paramlist.size()])});
            }

        } else {
//			String nodevalue = readNodeValue(beanelement, fieldname);
            Object value = getValue(beanelement, type, fieldname);
            if (value != null)
                method.invoke(bean, new Object[]{value});
        }
    }

    private static Object getValue(Element beanelement, Class type, String fieldname) throws Exception {
        Element fieldelement = beanelement.element(fieldname);
        if (fieldelement != null && fieldelement.elements() != null && fieldelement.elements().size() > 0) {
            return getElementBean(fieldelement, type);
        }
        String nodevalue = readNodeValue(beanelement, fieldname);
        if (nodevalue == null) {
            return null;
        }
        String typename = type.getSimpleName();
        if (typename.equals("String")) {
            return nodevalue;
        } else if (typename.equals("int") || typename.equals("Integer")) {
            return Integer.valueOf(nodevalue);
        } else if (typename.toLowerCase().equals("boolean")) {
            return Boolean.valueOf(nodevalue);
        } else if (typename.equals("String[]")) {
            return nodevalue.split(",");
        } else if (typename.toLowerCase().equals("long")) {
            return Long.parseLong(nodevalue);
        } else if (typename.toLowerCase().equals("float")) {
            return Float.parseFloat(nodevalue);
        } else if (typename.toLowerCase().equals("byte")) {
            return Byte.valueOf(nodevalue);
        } else {
            return nodevalue;
        }

    }

    private static String readNodeValue(Element parentelement,
                                        String elementname) {
        Element fieldelement = parentelement.element(elementname);
        if (fieldelement != null) {
            if (StringUtils.equals(elementname, "Content")) {
                return fieldelement.getText().trim().replaceAll("\n", "<br>");
            } else {
                return fieldelement.getText().trim().replaceAll("\\n", "");
            }
        }
        return null;
    }

    private static String getSetterMethodname(String fieldname) {
        return "set" + fieldname.substring(0, 1).toUpperCase()
                + (fieldname.length() > 1 ? fieldname.substring(1) : "");
    }

    public static Document getXMLDocument(InputStream input)
            throws DocumentException, SAXException,
            ParserConfigurationException {
        SAXReader reader = new SAXReader(getXMLReader());

        return reader.read(input);
    }

    private static Document getXMLDocument(String xmlContent)
            throws DocumentException, SAXException,
            ParserConfigurationException {
        SAXReader reader = new SAXReader(getXMLReader());

        return reader.read(new StringReader(xmlContent));
    }

}
